package com.elong.businesstravel.modules.login;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

import com.android.support.jhf.debug.DebugLog;
import com.android.support.jhf.handlerui.HandlerPostUI;
import com.android.support.jhf.handlerui.HandlerToastUI;
import com.android.support.jhf.network.NetworkClient;
import com.android.support.jhf.network.loopj.android.http.ResponseHandlerInterface;
import com.android.support.jhf.onClick.OnClickNetworkStatusListener;
import com.elong.businesstravel.R;
import com.elong.businesstravel.base.umeng.socialize.CustomShareDialog;
import com.elong.businesstravel.base.unionlogin.UnionLoginSucceed;
import com.elong.businesstravel.base.unionlogin.qq.QQUnionLogin;
import com.elong.businesstravel.base.unionlogin.sinaweibo.SinaUnionLogin;
import com.elong.businesstravel.base.unionlogin.weixin.WeChatUnionLogin;
import com.elong.businesstravel.base.utils.AppUserId;
import com.elong.businesstravel.base.utils.SaveUserOperate;
import com.elong.businesstravel.entitys.UnionLoginInfo;
import com.elong.businesstravel.modules.login.baseactivity.BaseLoginActivity;
import com.elong.businesstravel.protocol.login.MemberCheckLoginRequest;
import com.elong.businesstravel.protocol.login.MemberCheckLoginResponse;
import com.elong.businesstravel.protocol.login.MemberUnionLoginRequest;
import com.elong.businesstravel.protocol.login.MemberUnionLoginResponse;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;

/**
 * 登陆
 * 
 * @author lenovo
 * 
 */
public class LoginActivity extends BaseLoginActivity /*implements
		IWXAPIEventHandler*/ {

	private QQUnionLogin mQQUnionLogin;
	private SinaUnionLogin mSinaUnionLogin;
	private WeChatUnionLogin mWeChatUnionLogin;
	private UnionLoginInfo mUnionLoginInfo = new UnionLoginInfo();

	/** 1:标示联合登陆，0:标示手机号登陆 */
	private int mFlag = 0;

//	/** 用于微信联合登陆 */
//	private IWXAPI api;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);

		DebugLog.logI("LoginActivity onCreate");

		init();
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
//		api.handleIntent(intent, this);

		DebugLog.logI("LoginActivity onNewIntent");
	}

	@Override
	protected void init() {
		super.init();
		
		mApplication.mWeChatCode = null;

		mQQUnionLogin = new QQUnionLogin(mContext);
		mSinaUnionLogin = new SinaUnionLogin(mContext);
		mWeChatUnionLogin = new WeChatUnionLogin(mContext);

//		// 微信联合登陆
//		api = WXAPIFactory.createWXAPI(this, CustomShareDialog.WX_APPID, false);
//		api.handleIntent(getIntent(), this);

		setTitleNavBar("手机验证", null);

		setListener();
	}

	@Override
	protected void setListener() {

		ImageView oauthQQImageView = (ImageView) findViewById(R.id.oauthQQImageView);
		oauthQQImageView.setOnClickListener(new OnClickNetworkStatusListener(
				mContext) {

			@Override
			public void onClickNetworkSucceed(View view) {
				showWaitDialog("请等待...", null);
				mUnionLoginInfo.opentype = QQUnionLogin.OPEN_TYPE;
				mFlag = 1;
				mQQUnionLogin.onClickLogin();
			}

			@Override
			public void onClickNetworkFail(View view) {

			}
		});

		ImageView oauthWeixinImageView = (ImageView) findViewById(R.id.oauthWeixinImageView);
		oauthWeixinImageView
				.setOnClickListener(new OnClickNetworkStatusListener(mContext) {

					@Override
					public void onClickNetworkSucceed(View view) {
						showWaitDialog("请等待...", null);
						DebugLog.logI("微信联合登陆");
						mFlag = 1;
						mUnionLoginInfo.opentype = WeChatUnionLogin.OPEN_TYPE;
						mWeChatUnionLogin.onClickLogin();
//						finish();
					}

					@Override
					public void onClickNetworkFail(View view) {

					}
				});

		ImageView oauthWeiboImageView = (ImageView) findViewById(R.id.oauthWeiboImageView);
		oauthWeiboImageView
				.setOnClickListener(new OnClickNetworkStatusListener(mContext) {

					@Override
					public void onClickNetworkSucceed(View view) {
						showWaitDialog("请等待...", null);
						mUnionLoginInfo.opentype = SinaUnionLogin.OPEN_TYPE;
						mFlag = 1;
						mSinaUnionLogin.onClickLogin();
					}

					@Override
					public void onClickNetworkFail(View view) {

					}
				});

		Button startUseButton = (Button) findViewById(R.id.startUseButton);
		startUseButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mFlag = 0;
				StringBuilder errorStringBuilder = new StringBuilder();
				if (!checkStartUse(errorStringBuilder)) {
					// error
					HandlerToastUI.getHandlerToastUI(mContext,
							errorStringBuilder.toString());
				} else {
					memberCheckLogin();

				}
			}
		});

		mQQUnionLogin.setUnionLoginSucceedListener(new UnionLoginSucceed() {

			@Override
			public void onUnionLoginSucceed(UnionLoginInfo unionLoginInfo) {
				hideWaitDialog();
				unionLoginInfo.opentype = QQUnionLogin.OPEN_TYPE;
				memberUnionLogin(unionLoginInfo);
			}
		});

		mSinaUnionLogin.setUnionLoginSucceedListener(new UnionLoginSucceed() {

			@Override
			public void onUnionLoginSucceed(UnionLoginInfo unionLoginInfo) {
				hideWaitDialog();
				unionLoginInfo.opentype = SinaUnionLogin.OPEN_TYPE;
				memberUnionLogin(unionLoginInfo);
			}
		});
		mWeChatUnionLogin.setUnionLoginSucceedListener(new UnionLoginSucceed() {

			@Override
			public void onUnionLoginSucceed(UnionLoginInfo unionLoginInfo) {
				hideWaitDialog();
				unionLoginInfo.opentype = WeChatUnionLogin.OPEN_TYPE;
				memberUnionLogin(unionLoginInfo);
			}
		});

		super.setListener();
	}

	/**
	 * 联合登陆
	 * 
	 * @param unionLoginInfo
	 */
	private void memberUnionLogin(UnionLoginInfo unionLoginInfo) {
		mUnionLoginInfo = unionLoginInfo;
		NetworkClient.getNetworkClient().PostRequest(
				new MemberUnionLoginRequest(mContext, unionLoginInfo.openid,
						unionLoginInfo.opentype),
				new MemberUnionLoginResponse() {
					@Override
					public void onResponse(
							ResponseHandlerInterface responseHandlerInterface) {
						HandlerPostUI.getHandlerPostUI(new Runnable() {

							@Override
							public void run() {
								mMemberLogin = memberLogin;
								if ("0".equals(mMemberLogin.status)) {
									if (null != memberLogin) {
										// mMemberLogin.uid = "0";
//										 mMemberLogin.newuser = "0";//模拟老用户
										DebugLog.logI("memberLogin.uphone : " + memberLogin.uphone);
										DebugLog.logI("memberLogin.nickname : " + memberLogin.nickname);
										if (!TextUtils
												.isEmpty(memberLogin.uphone)) {
											SaveUserOperate.setLoginPhone(
													mContext,
													memberLogin.uphone);
										}
										if (!TextUtils
												.isEmpty(memberLogin.nickname)) {
											SaveUserOperate.setLoginNickName(
													mContext,
													memberLogin.nickname);
										}
										jumpActivity(1);
									}
								} else {
									HandlerToastUI.getHandlerToastUI(mContext,
											mMemberLogin.msg);
								}

							}
						});

					}
				});
	}

	/**
	 * 会员登陆,手机号登陆
	 */
	private void memberCheckLogin() {
		NetworkClient.getNetworkClient().PostRequest(
				new MemberCheckLoginRequest(mContext, mPhoneEditTextClearView
						.getEditText().getText().toString(),
						mYzmEditTextClearView.getEditText().getText()
								.toString()), new MemberCheckLoginResponse() {
					@Override
					public void onResponse(
							ResponseHandlerInterface responseHandlerInterface) {
						HandlerPostUI.getHandlerPostUI(new Runnable() {

							@Override
							public void run() {
								mMemberLogin = memberLogin;
								if ("0".equals(mMemberLogin.status)) {
									if (null != memberLogin) {
										AppUserId.setUserId(mContext,
												memberLogin.uid);

										jumpActivity(0);
									}
								} else {
									HandlerToastUI.getHandlerToastUI(mContext,
											mMemberLogin.msg);
								}

							}
						});

					}
				});
	}

	/**
	 * 跳转界面
	 * 
	 * @param flag
	 *            0:手机号获取验证码地跳转，1:联合登陆跳转
	 */
	private void jumpActivity(int flag) {
		if (0 == flag) {
			AppUserId.setUserId(mContext, mMemberLogin.uid);
			if ("0".equals(mMemberLogin.newuser)) {
				// 0 老用户直接返回，
				// 登陆成功
				setResult(RESULT_OK);
				finish();
			} else {
				//第一次注册
				MobclickAgent.onEvent(mContext,"First_Registered");
				// // 新用户跳转填写邀请码
				Intent intent = new Intent(mContext,
						RegisterSucceedActivity.class);
				intent.putExtra("flag", mFlag);
				startActivityForResult(intent, 0);
			}
		} else if (1 == flag) {
			int tempUid = 0;
			try {
				tempUid = Integer.parseInt(mMemberLogin.uid);
			} catch (Exception e) {
			}
			if (tempUid > 0) {
				AppUserId.setUserId(mContext, mMemberLogin.uid);
				// 老用户
				// 登陆成功
				setResult(RESULT_OK);
				finish();
			} else {
				// 新用户
				Intent intent = new Intent(mContext,
						RegisterSucceedActivity.class);
				intent.putExtra("flag", mFlag);
				intent.putExtra("MemberLogin", mMemberLogin);
				intent.putExtra("UnionLoginInfo", mUnionLoginInfo);
				startActivityForResult(intent, 0);
			}
		}
	}

	@Override
	protected void onStop() {
		super.onStop();
		hideWaitDialog();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		hideWaitDialog();
		
		if (null != mQQUnionLogin
				&& QQUnionLogin.OPEN_TYPE.equals(mUnionLoginInfo.opentype)) {
			mQQUnionLogin.onActivityResult(requestCode, resultCode, data);
		}

		if (null != mSinaUnionLogin
				&& SinaUnionLogin.OPEN_TYPE.equals(mUnionLoginInfo.opentype)) {
			mSinaUnionLogin.onActivityResult(requestCode, resultCode, data);
		}

		switch (requestCode) {
		case 0: {
			// 填写邀请码返回
			switch (resultCode) {
			case RESULT_OK: {
				// 成功发送邀请码
				setResult(RESULT_OK);
				finish();
				break;
			}
			case RESULT_CANCELED: {
				// 跳过邀请码
//				setResult(RESULT_OK);
//				finish();
				break;
			}
			default:
				break;
			}
			break;
		}
		default:
			break;
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		if(null != mApplication.mWeChatCode){
			hideWaitDialog();
			DebugLog.logI("微信登陆成功");
			mWeChatUnionLogin.getOpenId(mApplication.mWeChatCode);
			mApplication.mWeChatCode = null;
		}else {
//			HandlerToastUI.getHandlerToastUI(mContext, "微信授权失败");
		}
	}

//	@Override
//	public void onReq(BaseReq arg0) {
//		
//	}
//
//	@Override
//	public void onResp(BaseResp arg0) {
//		
//	}

}
